var base64 = new Base64();
var statisticalAnormal= {
	init : function(){
		var me = this;
		me.myMap=null;
		me.heatmapOverlay=null;
		//定义下面两个全局变量存储报警类型的id，和车辆的id，方便点击柱状图取出相应的数据
	    me.alarmKindIds=[];
	    me.vehicleIds=[];
	    me.alarmkindid; //设置一个报警类型的id；
	    me.startTime = "";
     	me.endTime = "";
     	me.alarmKindId = "";
     	me.vehicleId = "";
		me.myChart=null;
		me.initQueryTime(); //初始化时间
		me.initAlarmKind();       //初始化类型
		me.initVehicleUnitList(); //初始化企业
		me.initVehicleList();    //初始化司机
		me.time=[];
		me.behavior = me.chartInit();//barChart
		me.pieChart = this.initPieChart();
		me.initEcharts();
		me.loadTableTitle();
		me.queryStatisticalAnomalyTable();
		
	    me.initEvent();
	},
    
	initEcharts : function(){
		var me=this;
		me.myChart = echarts.init(document.getElementById('speedCharts'));
     	var option = {
    		    xAxis: {
    		    	type : 'category',
    	            boundaryGap : false,
    		        data:me.time 
    		    },
    		    grid:{
    		    	x:30,
    		    	y:30,
    		    	x2:5,
    		    	y2:5
    		    	
    		    },
    		    calculable : true,
    		    tooltip: {
    		        trigger: 'axis',
    		        formatter: function (params) {
    		            params = params[0];
    		            return "时间:"+params.name+"<br/>"+"速度"+params.value;
    		        },
    		        axisPointer: {
    		            animation: false
    		        }
    		    },
    		    yAxis: {
    		        name : '速度(km/h)',
    			    type : 'value',

    			    max : 150,
    			    data : [30,60,90,120,150]
    		    },
    		    series: [
    		        {
    		            name:'速度',
    		            type:'line',
    		            smooth:true,
    		            stack: 'a',
    		            data: [0]
    		        }
    		    ]
    		};
    	me.myChart.setOption(option);
    },
    initQueryTime:function(){
        var todayDate = new Date();
        var todayDateStr=todayDate.getFullYear()+"-"+(todayDate.getMonth()+1)+"-"+todayDate.getDate();  
        //$("#inputEndDate").val(todayDateStr);
        	
        var beforeDate = new Date(todayDate); //前一天
	    var yyyy = beforeDate.getFullYear(), mm = (beforeDate.getMonth() + 1).toString(), dd = beforeDate.getDate().toString();
	    if (mm.length == 1) {
	        mm = '0' + mm;
	    }
	    if (dd.length == 1) {
	        dd = '0' + dd;
	    }
        $("#inputStartDate").val(yyyy + '-' + mm + '-' + dd);
        $("#inputEndDate").val(yyyy + '-' + mm + '-' + dd);
      },
    /**
     * 绑定时间（查询，导出）
     */
    initEvent : function(){
    	var me = this;
    	var map = new BMap.Map("container");    // 创建地图实例
	    var point = new BMap.Point(113.26006, 23.13399);
	    map.centerAndZoom(point, 12);           // 初始化地图，设置中心点坐标和地图级别
	    map.enableScrollWheelZoom(); 			// 允许滚轮缩放
	    me.myMap = map;
	   	$("#selectVehicleUnitSel").change(function(){
			$('#vehicleSelDiv').html("<select class='query-select' id='selectVehicleSel'></select>");
			var unitId = $(this).children('option:selected').val(); 
			if(unitId!=' '&&unitId!=null){
				me.initVehicleList(unitId);
			}else{
				me.initVehicleList();
			}
		});
    	$("#queryBtn").click(function(){
    		me.queryStatisticalAnomalyTable();
    	});
    	$("#exportExcel").click(function(){
    		me.exportStatisticalAnomaly();
    	});
    	$("#confirmOK").on("click",function(){
			$("#velidateModal").modal('hide');
			me.exportExcel();
		});
      $('.detail-report').on('click',"img[name='pictureShowBtn']",function(){
     		var alarmType = "0";
     		var vehicleId = $(this).attr('vehicleId');
     		var alarmTime = $(this).attr('alarmTime');
			var url = appCtx + "/alarm/showPicture.html?alarmTime="+alarmTime+"&vehicleId="+vehicleId+"&alarmType="+alarmType;
			$.ajax({
	        	   url:url,
	        	   type: 'POST',
	        	   async:true,
	        	   cache:false,
	        	   success:function(data){
	        		   	if (data) {
	        		   		var dataJson = JSON.parse(data);
							var imgUrl = dataJson.imgUrl;
							var isHave = dataJson.isHave;
							if (parseInt(isHave)==1) {
								if (parseInt(dataJson.mediaFormat) == 0) {
									$("#modalTitle").html("图片展示");
									$("#msg").hide();
									$("#largeImgage").show();
									$("#largeImgage").attr("src",imgUrl);
									$("#pictureModal").modal('show');
								}else if (parseInt(dataJson.mediaFormat) == 5){
									$("#showVedio").attr("src",imgUrl);
									$("#vedioModal").modal('show');
								}
							}else{
								$("#largeImgage").hide();
								$("#modalTitle").html("取证展示");
								$("#msg").show();
								$("#pictureModal").modal('show');
							}
	        		   }
	        	   }
	           });
		});
        $('.detail-report').on('click',"img[name='trackPlayBtn']",function(){
        	$("#speedDiv").show();
     		var vehicle_no = $(this).attr('vehicle_no');
     		var vehicle_no_color = $(this).attr('vehicle_no_color');
     		var alarmTime = $(this).attr('alarmTime');
        	var alarm_time = new Date((alarmTime).replace(/-/g,"/"));
        	var gettime = new Date(alarm_time).getTime();
        	var startDateTime = global.getTime(new Date(gettime - 60000));
        	var endDateTime =  global.getTime(new Date());
       // 	var endDateTime = global.getTime(new Date(gettime + 600000));
     		//var src = appCtx+"views/business/gis/trackPlayBackCommon.jsp?vehicleId="+vehicle_no_color+"&startTime="+startDateTime+"&endTime="+endDateTime+"";
     		//$("#trackPlayBackIframe").attr('src',src);
     		$.ajax({
        		type : 'post',
        		async : false,
        		url : appCtx+'gis/playback/queryTrackList.html?vehicle_no_color='+vehicle_no_color+"&start_time="+startDateTime+"&end_time="+endDateTime,
        		cache : false,
        		dataType : "JSON",
        		data:{},
        		success : function(result) {
        			if(result&&result.rows>0){
        				me.time = [];
	        			me.speed = [];
        				for(var i=0;i<result.rows.length;i++){
        					me.time.push(result.rows[i].gpsTime);
	        				me.speed.push(result.rows[i].gpsSpeed);
        				}
        				
        				me.myChart.setOption({
                            xAxis: {
                                data: me.time
                            },
                            series: [{
                                name:'速度',
                                data: me.speed
                            }]
                        });
        				
        				var lnglatArr = new Array();
        				for(var i=0;i<result.length;i++){
        					var lng = result[i].longitudeD;
        					var lat = result[i].latitudeD;
        					var lnglat = new Array();
            				lnglat.push(lng);
            				lnglat.push(lat);
            				lnglatArr.push(lnglat);
        				}
        				var carPic = appCtx + "resources/images/mapTool/car1.png";//TODO 无法获取车辆类型，暂时先取0
        				me.initMapNoMarker(carPic,lnglatArr,vehicle_no);
        			}else{
        				var map = new AMap.Map("container", {
        			        resizeEnable: true,
        			        center: [106.71,26.57],
        			        zoom: 11
        			    });
        				var infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)}); 
        	    		me.infoWindow = infoWindow;
        	    		marker = new AMap.Marker({
        	    		    map: map,
        	    		    position:[106.68,26.57],
        	    		    icon: "",
        	    		    offset: new AMap.Pixel(-15, -10),
        	    		    autoRotation: true
        	    		});
        	    		marker.content = '暂无定位数据';
        	    		infoWindow.setContent(marker.content);
        	    		infoWindow.open(map, marker.getPosition());
        			}
        		}
        	});
     		
     	});
    },
    initMapNoMarker: function(carPic,lineArr,vehicle_no){
		var map = new AMap.Map("container", {
	        resizeEnable: true,
	        center: lineArr[0],
	        zoom: 14
	    });
	    startMarker = new AMap.Marker({
	        map: map,
	        position: lineArr[0],
	        icon: global.url.domain + "gps-web/resources/images/mapTool/p_start.png",
	        offset: new AMap.Pixel(-15, -30)
	    });
	    var content2 ='车牌：'+vehicle_no;
	    var infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)});
	    infoWindow.setContent(content2);
	    infoWindow.open(map, startMarker.getPosition());
	    endMarker = new AMap.Marker({
	        map: map,
	        position: lineArr[lineArr.length-1],
	        icon: global.url.domain + "gps-web/resources/images/mapTool/p_end.png",
	        offset: new AMap.Pixel(-15, -30)
	    });
		 marker = new AMap.Marker({
		        map: map,
		        position:  lineArr[0],
		        icon: carPic,
		        offset: new AMap.Pixel(-26, -13),
		        autoRotation: true
		    });
	    // 绘制轨迹
	    var polyline = new AMap.Polyline({
	        map: map,
	        path: lineArr,
	        strokeColor: "#00A",  //线颜色
	        // strokeOpacity: 1,     //线透明度
	        strokeWeight: 3,      //线宽
	        // strokeStyle: "solid"  //线样式
	    });
	    var passedPolyline = new AMap.Polyline({
	        map: map,
	        // path: lineArr,
	        strokeColor: "#F00",  //线颜色
	        // strokeOpacity: 1,     //线透明度
	        strokeWeight: 3,      //线宽
	        // strokeStyle: "solid"  //线样式
	    });
	    marker.on('moving',function(e){
	        passedPolyline.setPath(e.passedPath);
	    })
	    map.setFitView();
	    marker.moveAlong(lineArr, 20000);
	},
    /**
     * 获取查询参数
     * @returns {Array}
     */
	getParams : function(){
	
		var alarmKindId= $('#selectAlarmtype').val();
		var unitid = $('#selectVehicleUnitSel').val();//企业id
		var vehicleId = $("#selectVehicleSel").val();
		var startTime = $('#inputStartDate').val(); 
		var endTime = $('#inputEndDate').val();
		// 查询参数
		var params = [ 
		    {
		      name:'alarmKindId',
		      value:alarmKindId
		    },{
			name : 'vehicleId',
			value : vehicleId
		},{
			name : 'unitId',
			value : unitid
		}, {
			name : 'startTime',
			value : startTime
		}, {
			name : 'endTime',
			value : endTime
		} ];
		return params;
	},
	initAlarmKind:function(){
		var me = this;
    	$.ajax({
    		type : 'get',
    		url:appCtx + "/alarm/getAlarmKind.html?time="+ new Date().getTime(),
    		cache : false,
    		dataType : "JSON",
    		success : function(data) {			
    			if(data){
    				 var selectStr="<option value=''>请选择报警类型</option>";
    				for(var i=0;i<data.length;i++){
    					selectStr+="<option value='"+data[i].id+"'>"+data[i].name+"</option>";
    				}
    				$('#selectAlarmtype').html(selectStr);		
    				$("#selectAlarmtype").select2();
    				
    			}
    		}
    	});
	},
	initVehicleUnitList:function(){
    	var me = this;
    	$.ajax({
    		type : 'get',
    		url : appCtx + "/system/common/loadUserUnit.html",
    		cache : false,
    		dataType : "JSON",
    		success : function(data) {			
    			if(data){
    				 var selectStr="<option value=''>请选择企业</option>";
    				for(var i=0;i<data.length;i++){
    					selectStr+="<option value='"+data[i].entId+"'>"+data[i].entName+"</option>";
    				}
    				$('#selectVehicleUnitSel').html(selectStr);		
    				$("#selectVehicleUnitSel").select2();
    				$("#selectVehicleUnitSel").change(function(){
    					var entId = $(this).children('option:selected').val(); 
    					if(entId!=''&&entId!=null){
    						me.initVehicleList(entId);
    					}else{
    						me.initVehicleList();
    					}
    				});
    			}
    		}
    	});
    },
	initVehicleList:function(entId){
    	var urlTemp;
    	if(entId){
    		urlTemp="/system/common/loadUserVehicle.html?enterprise_id="+entId;
    	}else{
    		urlTemp="/system/common/loadUserVehicle.html";
    	}
    	$.ajax({
    		type : 'get',
    		
    		url : appCtx + urlTemp,
    		cache : false,
    		dataType : "JSON",
    		success : function(data) {			
    			if(data){
    				$('#vehicleSelDiv').html("<select class='query-select' id='selectVehicleSel'></select>");
    				var selectStr="";
    				selectStr+="<option value=''>全部车辆</option>";
    				$.each(data,function(entryIndex,entry) {
    					selectStr+="<option value='"+entry.id+"'>"+entry.vehicle_no+"</option>";
    				});
    				
    				$('#selectVehicleSel').html(selectStr);
    				
    				$("#selectVehicleSel").select2();

    			}
    		}
    	});
    },
     
    
    /**
     * 初始化chart
     * @returns 
     */
    chartInit : function(){
    	var me = this;
    	var percent = 100;
    	
        var option = {
            tooltip : {
                trigger: 'axis',
                show: true,
		        axisPointer : {            // 坐标轴指示器，坐标轴触发有效
		        	show: false,
		            type : 'none'        // 默认为直线，可选为：'line' | 'shadow'
		        },
                formatter:function(a){
		        	if(a[0].name==''){
		        		return;
		        	}
		        	var relVal = "";
		        	relVal = a[0].name+"："+a[0].value+"次";
		        	return relVal;
		        }
            },
            color:['#FF7F00'],
            legend: {
                data:[]
            },
            /*grid: {
		        left: '3px',
		        top:'10%',
		        right: '33px',
		        containLabel: true
		    },*/
            calculable : true,
            xAxis : [
                {  
                    type : 'category',
                    data : []
                }
            ],
            yAxis : [
                {
                	name :'报警次数',
                    type : 'value',
                
                }
            ],
            series : [
                {
                    name:'',
                    type:'bar',
                    data:[],
                    barwidth:30
                    
                }
            ],
		    dataZoom: [{
		        type: 'inside',
		        start: 0,
		        end: 100
		    }, {
		        start: 0,
		        end: 100,
		        fillerColor:'#A3E1A3',
		        handleColor:'#83A7D1'
		    }]
        };
        var myChart = echarts.init(document.getElementById('barChart'));
        myChart.setOption(option);
        window.onresize = myChart.resize;
        
        myChart.on('click', function(param){
	        	var alarmKindId= $('#selectAlarmtype').val();
	 		   // var vehicleId = $("#selectVehicleSel").val();
		    var  vehicleId = me.vehicleIds[param.dataIndex];
		    me.vehicleId = vehicleId;
	      	var name = param.data.name;
	      	var unitid = $('#selectVehicleUnitSel').val();//企业id
	      	var startTime = $('#inputStartDate').val(); 
			var endTime = $('#inputEndDate').val();
	      	me.queryPieChartData(alarmKindId,unitid,startTime,endTime,vehicleId);
	 	    me.reloadTable(alarmKindId,unitid,vehicleId);
         });
    
        
        return {
        	refash : function(option){
                myChart.setOption(option);
        	},
        	option : option,
        	chartDrivingDom : myChart
        };
    },
    
    
    queryBarChartData: function(alarmKindId,unitId,vehicleId,startTime,endTime,name){
		var me = this;
		$.ajax({
			type : 'get',
			async : true,
			url : appCtx+"/report/statisticalAnomaly/querycharData.html",
			data:{
				alarmKindId:alarmKindId,
				unitId:unitId,
				vehicleId:vehicleId,
				startTime:startTime,
				endTime:endTime
			},
			cache : false,
			dataType : "JSON",
			success : function(data) {
				var option = me.behavior.option;
				if(data != null){
					option.xAxis[0].data = data.xAixs;
					option.series[0].data = data.yAxis;
					me.alarmKindIds=data.alarmKindIds;
				    me.vehicleIds=data.vehicleIds;
					var name1 = $('#selectAlarmtype option:selected').text();
					if(name1 == '请选择报警类型'){
						option.series[0].name= '';
						option.legend.data=[];
					}else{
						option.series[0].name= name1;
						option.legend.data=[name1];
					}
					me.behavior.refash(option);
					//me.queryStatisticalAnomalyTable(me.alarmKindIds[0],me.vehicleIds[0]);
				}
		
			}
		});
	},
    

	initPieChart: function(){
		var me = this;
		option = {
			    title : {
			        text: '',
			        subtext: '',
			        x:'center',
			        show:false
			    },
			    tooltip : {
			        trigger: 'item',
			        formatter: "{b} :{c}次 "
			       
			    },
			    legend: {
			        orient: 'vertical',
			        left: 'left',
			        data: [],
			        show: false
			    },
			    series : [
			        {
			            name: '',
			            type: 'pie',
			            radius : '75%',
			            center: ['50%', '50%'],
		            	labelLine: {
		                normal: {
		                    show: false
		                }
		            	},
		            	label: {
		                normal: {
		                    show: false
		                }
		            	},
			            data:[],
			            itemStyle: {
			                emphasis: {
			                    shadowBlur: 10,
			                    shadowOffsetX: 0,
			                    shadowColor: 'rgba(0, 0, 0, 0.5)'
			                },
			                normal:{ 
				                  label:{ 
				                    show: true, 
				                    formatter: '{b}({d}%)' 
				                  }, 
				                  labelLine :{show:true} 
				            }
			            }
			             
			        }
			    ],
			    color: ['rgb(255,165,0)','rgb(205,133,63)','rgb(165,42,42)','rgb(255,20,147)','rgb(199,21,133)','rgb(160,32,240)','rgb(139,137,137)','rgb(122,103,238)','rgb(141,182,205)','rgb(139,0,139)','rgb(144,238,144)','rgb(139,0,139)','rgb(238,58,140)','rgb(205,16,118)','rgb(255,114,86)','rgb(139,101,8)','rgb(50,205,50)']
			};
		
		 var myChart = echarts.init(document.getElementById('pieChart'));
         myChart.setOption(option);
         window.onresize = myChart.resize;
         myChart.on('click', function(param){
        	 var alarmKindId = param.data.id;
          	if(typeof(alarmKindId) == 'undefined'){
          		alarmKindId =  $('#selectAlarmtype').val();
          	}
          	me.alarmkindid = alarmKindId;//全局变量复值
          	
          	var name = param.data.name;
          	var unitid = $('#selectVehicleUnitSel').val();//企业id
     		var vehicleId =  me.vehicleId;
     	   var startTime = $('#inputStartDate').val(); 
     	   var endTime = $('#inputEndDate').val();
            // me.queryBarChartData(alarmKindId,unitid,vehicleId,startTime,endTime,name);
             me.reloadTable(alarmKindId,unitid,vehicleId);	
            
         });
         return {
         	refash : function(option){
                 myChart.setOption(option);
         	},
         	option : option,
         	pieChartDom : myChart
         };
	},
	queryPieChartData: function(alarmKindId,unitId,startTime,endTime,vehicleId){
		var me = this;
		$.ajax({
			type : 'get',
			async : true,
			url : appCtx+"/report/statisticalAnomaly/queryPieData.html",
			data:{
				alarmKindId:alarmKindId,
				unitId:unitId,
				startTime:startTime,
				endTime:endTime,
				vehicleId:vehicleId
			},
			cache : false,
			dataType : "JSON",
			success : function(data) {
				var option = me.pieChart.option;
				var option1 = me.behavior.option;
				var alarmKindId = null;
				if(data == null || data.length === 0){
				   var name = $('#selectAlarmtype option:selected').text();
				   if(name == '请选择报警类型'){
					   name = "无数据";
				   }
				   option.series[0].data = [{name:name,'value':0}];
					me.pieChart.refash(option);
					var dataRows ={
						rows:[],
		  		     	total:0,
		  		    		page:1
					}
					$("#objTable").flexAddData(dataRows);
				}else{
					option.series[0].data = data;
					me.pieChart.refash(option);
				    alarmKindId = data[0].id;
		         	me.alarmkindid = alarmKindId;//全局变量复值
					var name = data[0].name;
		         	var unitid = $('#selectVehicleUnitSel').val();//企业id
			    		var vehicleId = $("#selectVehicleSel").val();
			    		var startTime = $('#inputStartDate').val(); 
			    		var endTime = $('#inputEndDate').val();
					//me.queryBarChartData(alarmKindId,unitid,vehicleId,startTime,endTime,name);
					//me.reloadTable(alarmKindId,vehicleId,startTime,endTime);
				}
			}
		});
		
	},
    

      //以下是新添加的
      
      getColumn:function(){
      	return [{
              display : '序号',
              name : 'rowNo',
              width : 8,
              sortable : false,
              align : 'left'
          },{
              display : '车牌号',
              name : 'vehicle_no',
              width : 17,
              sortable : false,
              align : 'left',
              showTitle : 'vehicle_no'
          },{
              display: '报警类型',
              name: 'alarmType',
              width: 15,
              sortable: false,
              align: 'left',
              showTitle:true
          },{
              display: '报警来源',
              name: 'alarmSource',
              width: 15,
              sortable: false,
              align: 'left',
              showTitle:true
             
          },{
              display: '报警时间',
              name: 'alarmTime',
              width: 25,
              sortable: false,
              align: 'left', 
              showTitle:true
          },{
              display :'颜色',
              name : 'vehicle_color',
              width : 0,
              sortable : false,
              align : 'left',
            	  hide:'true'
           },{
          	display : '轨迹',
              name : 'Handler',
              width : 11,
              sortable : false,
              align : 'center',
              paramcolnames:['vehicle_no','vehicle_color','alarmTime'],
              handlefunction:function(vehicle_no,vehicleColor,alarmTime){
            	    
            	    var vehicle_no_color = base64.encode(vehicle_no+"_"+vehicleColor);
              	var handleStr = '<div style="padding:0px;float:left;width:35px;height:19px;cursor:pointer;"><img vehicle_no_color="'
              		+ vehicle_no_color + '" alarmTime="' + alarmTime + '" vehicle_no="' + vehicle_no
              		+ '" name="trackPlayBtn" src="'
              		+ global.url.domain + 'gps-web/resources/images/track.png" title="轨迹显示"><div>';
         		
          		return handleStr;
              }
          },{
        	  display : '取证',
              name : 'picture',
              width : 9,
              sortable : false,
              align : 'center',
              paramcolnames:['vehicle_id','alarmTime','alarmType'],
              handlefunction:function(vehicleid,alarmTime,alarmType){
              	var handleStr = '<div style="padding:0px;float:left;width:35px;height:19px;cursor:pointer;"><img vehicleid="'
              		+ vehicleid + '" alarmTime="' + alarmTime + '" alarmType="' + alarmType
              		+ '" name="pictureShowBtn" src="'
              		+ global.url.domain + 'gps-web/resources/images/track.png" title="照片/视频证据 "><div>';
         		
          		return handleStr;
          
          }
          }
          ]
      },
      loadTableTitle:function(){
    	  var me = this;
    	  var startTime=$("#inputStartDate").val();
          var endTime=$("#inputEndDate").val();
          var params = [{
	          	name:'startTime',
	  			value:startTime
	  		},{
	  			name:'endTime',
	  			value:endTime,
	  		},{
	  			name:'alarmKindId',
	  			value:""
	  		},{
	  			name:'vehicleId',
	  			value:""
	       }]
      		me.startTime = startTime;
         	me.endTime = endTime;
         	me.alarmKindId = "";
         	me.vehicleId = "";
    	  $("#objTable").flexigrid({
    		    url: appCtx + "/report/statisticalAnomaly/queryStatisticalAnomalyListTable.html?" + new Date().getTime(),
	            method:'post',
	            params: params,
  	            dataType : 'json',
  	            colModel :this.getColumn() ,
  	            usepager : true,// 是否分页，默认为true。
  	            singleSelect : true,
  	            titDisplay: false,
  	            resizable : false,
  	            height:$('#chartDriving2').height()-86,
  	            widthType:'%',
  	            width:$('.detail-report').width(),
  	            rp : 10, //每页记录数，默认为10
  	            rpOption:[10,20,50,100],
  	            sortname:'alarmTime',
  	            sortorder:'desc',
  	            onSuccess:function(data){
  	            	if (data.rows&&data.rows.length>0) {
  	            		if (me.heatmapOverlay) {
  							me.myMap.removeOverlay(me.heatmapOverlay);
  						}
  	             		me.statisticalAnomalLoca(data.pointList);
  					}else{
  						if (me.heatmapOverlay) {
  							me.myMap.removeOverlay(me.heatmapOverlay);
  							me.myMap.centerAndZoom(new BMap.Point(113.26006, 23.13399), 12);
  						}
  					}
	           }
	        });	 
	},
	statisticalAnomalLoca:function(list){
    	var me = this;
    	var points = [];
		for (var i = 0; i < list.length; i++) {
			if (list[i].indexOf("_")>0) {
				var point = list[i].split("_");
				points.push({
					lng: parseFloat(point[0]),
					lat:parseFloat(point[1]),
					count: 80
				})
			}
		}
		//百度地图
	    var heatmapOverlay = new BMapLib.HeatmapOverlay({"radius":20});
	    me.heatmapOverlay = heatmapOverlay;
	    me.myMap.addOverlay(heatmapOverlay);
		heatmapOverlay.setDataSet({data:points,max:100});
		me.myMap.centerAndZoom(new BMap.Point(points[0].lng, points[0].lat), 12);
    },
    queryStatisticalAnomalyTable:function(){
     	var me = this;
     	var alarmKindId = $('#selectAlarmtype').val();
	   	var vehicleId=$("#selectVehicleSel").val();
	   	var unitId=$("#selectVehicleUnitSel").val();
      	var startTime=$("#inputStartDate").val();
       	var endTime=$("#inputEndDate").val();
       	
       	var end_str = (endTime).replace(/-/g,"/");//一般得到的时间的格式都是：yyyy-MM-dd hh24:mi:ss，所以我就用了这个做例子，是/的格式，就不用replace了。  
      	var end_date = new Date(end_str);//将字符串转化为时间  
      	//开始时间  
      	var sta_str = (startTime).replace(/-/g,"/");  
      	var sta_date = new Date(sta_str); 
      	var num = (end_date-sta_date)/(1000*3600*24);//求出两个时间的时间差，这个是天数  
      	var days = parseInt(Math.ceil(num));//转化为整天（小于零的话剧不用转了） 
      	if(endTime < startTime){
    		global.ajaxLoading.pop("查询结束时间不能小于开始时间",false,2000);
    		return;
    	}
      	if(days>3){
      		global.ajaxLoading.pop("查询时间不能超过3天",false,2000);
      		return;
      	}
      	me.queryPieChartData(alarmKindId,unitId,startTime,endTime,vehicleId);
      	me.queryBarChartData(alarmKindId,unitId,vehicleId,startTime,endTime);
      	me.reloadTable(alarmKindId,unitId,vehicleId);
    },
	reloadTable:function(alarmKindId,unitId,vehicleId){
		var me = this;
		$("#speedDiv").hide();
 	   	//$("#container").show();
     	//$("#trackPlayBackIframe").hide();
		var startTime=$("#inputStartDate").val();
       	var endTime=$("#inputEndDate").val();
       	me.startTime = startTime;
       	me.endTime = endTime;
       	me.alarmKindId = alarmKindId;
       	me.vehicleId = vehicleId;
        var params = [{
        	name:'startTime',
			value:startTime
		},{
			name:'endTime',
			value:endTime,
		},{
			name:'alarmKindId',
			value:alarmKindId
		},{
			name:'unitId',
			value:unitId
		},{
			name:'vehicleId',
			value:vehicleId
        }]
        $("#objTable").flexOptions({
      	    url: appCtx + "/report/statisticalAnomaly/queryStatisticalAnomalyListTable.html?" + new Date().getTime(),
      	    newp: 1,// 设置起始页
      	    params: params
        }).flexReload();// 重新加载
	},
	   /**
     * 导出列
     * @returns {Array}
     */
	exportColum:function(){
    	return [{
            display : '序号',
            name : 'rowNo',
            width : 60,
            align : 'left'
        },{
            display : '车牌号',
            name : 'vehicleNo',
            width : 200,
            align : 'left',
        },{
            display: '报警类型',
            name: 'alarmType',
            width: 120,
            align: 'left',
        },{
            display: '报警来源',
            name: 'alarmSource',
            width: 120,
            align: 'left',
        },{
            display: '报警时间',
            name: 'alarmTime',
            width: 250,
            align: 'left', 
        }]
    },
    /**
     * 导出
     */
    exportStatisticalAnomaly: function(){
		var me=this;
		var options = $("#objTable").getOptions();
		if(typeof(options.data) != 'undefined'){
			var total = options.data.rows;
			if(total && total.length > 0){
				var pages = options.pages;
				//设置默认的开始结束页
				$("#StartPageIndex").val(1);
				$("#EndPageIndex").val(pages);
				$("#exportModal").modal("show");
			}
			else{
				global.ajaxLoading.pop("无导出数据",false,2000);
				return;
			}
		}
		else{
			global.ajaxLoading.pop("无导出数据",false,2000);
			return;
		}
	},
    exportExcel : function(){
    	var me =this;
    	var options = $("#objTable").getOptions();
		//总记录数
		var total = options.total;
		//开始页数
		var StartPage=$("#StartPageIndex").val();
		//结束页数
		var EndPage=$("#EndPageIndex").val();
		if(!StartPage || StartPage<=0){
			global.ajaxLoading.pop("起始页不能为空或是小于0",false,2000);
			return;
		}
		if(!EndPage || EndPage<=0){
			global.ajaxLoading.pop("结束页不能为空或是小于0",false,2000);
			return;
		}
		
		if(EndPage<StartPage){
			global.ajaxLoading.pop("结束页要大于起始页",false,2000);
			return;
		}
		$('#exportModal').modal('hide');
		global.ajaxLoading.pop("正在导出,请稍后.....",false,2000);
		//每页大小
		var pagesize = options.rp;
     	var data1 = JSON.stringify(statisticalAnormal.exportColum());
     	var header2 = JSON.parse(data1);
    	   var headerWidth = $('.detail-report').width();
		for(var i=0;i<header2.length;i++){
			header2[i].width = Math.ceil(headerWidth / 800 * header2[i].width);
		}
		header2.splice(header2.length,1);
		var header3 = JSON.stringify(header2);
		var imageUrl = statisticalAnormal.behavior.chartDrivingDom.getDataURL({
			type: 'png',
		    pixelRatio: 1
		}); 
		 var imageUrl2 = me.pieChart.pieChartDom.getDataURL({
			type: 'png',
		    pixelRatio: 1
		});
		//表头
		var colModelList=new Array();
		colModelList.push(header3);
		var colModel= $.toJSON(colModelList);
		//图片
		var imgsrcList=new Array();
		imgsrcList.push(imageUrl);
		imgsrcList.push(imageUrl2);
		var imgsrc= $.toJSON(imgsrcList);
		var param =  {
				page:StartPage,
				pageSize:(EndPage - StartPage + 1) * pagesize,
				startTime:me.startTime,  
				endTime:me.endTime,  
				unitId:$("#selectVehicleUnitSel").val(),
				vehicleId:me.vehicleId,
				alarmKindId:me.alarmKindId,
				colModel:colModel,
				title:"异常驾驶行为分析导出",
				imgsrc:imgsrc
		};
		post(appCtx+"/report/statisticalAnomaly/exportStatisticalAnomaly.html",param);
	},

}
statisticalAnormal.init();